<template>
  <div class="restaurant-layout">
    <!-- 区域选择 -->
    <div class="header">
      <div class="tab-group">
        <div 
          class="tab-item"
          :class="{ active: activeRegion === 'all' }"
          @click="handleRegionChange('all')"
        >
          全部
        </div>
        <div 
          v-for="region in regions" 
          :key="region.regionId"
          class="tab-item"
          :class="{ active: activeRegion === region.regionId + '' }"
          @click="handleRegionChange(region.regionId + '')"
        >
          {{ region.regionName }}
        </div>
      </div>
    </div>

    <!-- 餐桌布局区域 -->
    <div class="tables-container">
      <!-- 餐桌统计信息 -->
      <div class="tables-stats">
        <div class="stats-card">
          <div class="stats-title">当前区域空闲餐桌</div>
          <div class="stats-value">{{ getCurrentRegionAvailableTables }}</div>
        </div>
        <div class="stats-card">
          <div class="stats-title">总空闲餐桌</div>
          <div class="stats-value">{{ getTotalAvailableTables }}</div>
        </div>
        <div class="stats-card">
          <div class="stats-title">当前区域总餐桌</div>
          <div class="stats-value">{{ getCurrentRegionTotalTables }}</div>
        </div>
      </div>

      <div class="tables-grid">
        <div 
          v-for="board in filteredBoards" 
          :key="board.boardId"
          class="table-card"
          :class="[
            getTableStatusClass(board.boardStatus),
            { 'cursor-not-allowed': !isTableClickable(board) }
          ]"
          @click="handleTableClick(board)"
        >
          <div class="card-header">
            <span class="table-name">{{ board.boardName }}</span>
            <span class="status-tag">{{ getStatusText(board.boardStatus) }}</span>
          </div>
          <div class="card-body">
            <div class="info-row">
              <span class="info-item">
                <i class="el-icon-user"></i>
                {{ board.seat }}人桌
              </span>
              <span class="info-item">
                <i class="el-icon-tickets"></i>
                {{ board.boardType }}
              </span>
            </div>
            <div class="time-info">
              <i class="el-icon-time"></i>
              {{ calculateDiningDuration(board.boardId) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="orderDialogVisible"
      :title="currentBoard ? `${currentBoard.boardName} 订单信息` : '订单信息'"
      width="500px"
      destroy-on-close
      class="order-dialog"
    >
      <el-scrollbar height="calc(90vh - 150px)">
        <div v-if="currentOrder" class="order-details">
          <div class="order-header">
            <div class="order-number">订单号：{{ currentOrder.orderId }}</div>
            <div class="order-status" :class="{
              'status-paid': currentOrder.orderStatus === 'PAID',
              'status-unpaid': currentOrder.orderStatus === 'TO_BE_PAID',
              'status-canceled': currentOrder.orderStatus === 'CANCELED'
            }">{{ getOrderStatusText(currentOrder.orderStatus) }}</div>
          </div>
          
          <el-divider />
          
          <div class="order-info">
            <div class="info-group">
              <div class="info-label">开单时间</div>
              <div class="info-value">{{ formatTime(currentOrder.placeOrderTime) }}</div>
            </div>
            <div class="info-group">
              <div class="info-label">订单金额</div>
              <div class="info-value">
                <div>总额：¥{{ currentOrder.totalAmount }}</div>
                <div>优惠：¥{{ currentOrder.discountAmount }}</div>
                <div class="price">实付：¥{{ currentOrder.payableAmount }}</div>
              </div>
            </div>
            <div class="info-group">
              <div class="info-label">订单类型</div>
              <div class="info-value">{{ currentOrder.orderType === 1 ? '堂食' : '外卖' }}</div>
            </div>
          </div>
          
          <el-divider />
          
          <div class="dishes-list">
            <div class="list-header">
              <span>已点菜品</span>
              <span>{{ currentOrder.items?.length || 0 }}道菜</span>
            </div>
            <el-scrollbar max-height="300px">
              <div 
                v-for="item in currentOrder.items" 
                :key="item.orderItem.itemId" 
                class="dish-item"
              >
                <div class="dish-info">
                  <div class="dish-main">
                    <span class="dish-name">{{ item.dish.dishName }}</span>
                    <span class="dish-quantity">x{{ item.orderItem.quantity }}</span>
                  </div>
                  <div v-if="item.dish.dishDescribe" class="dish-describe">
                    {{ item.dish.dishDescribe }}
                  </div>
                </div>
                <div class="dish-price-info">
                  <span class="dish-price">¥{{ item.dish.price * item.orderItem.quantity }}</span>
                  <span class="dish-unit-price">¥{{ item.dish.price }}/份</span>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <div v-if="currentOrder.remark" class="order-remark">
            <el-divider />
            <div class="remark-title">备注</div>
            <div class="remark-content">{{ currentOrder.remark }}</div>
          </div>
        </div>
        <div v-else class="no-order">
          <el-empty description="暂无订单信息">
            <el-button type="primary" @click="orderDialogVisible = false">
              知道了
            </el-button>
          </el-empty>
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { TabPaneName } from 'element-plus'
import { ElMessage } from 'element-plus'
import { regionApi, boardApi, orderApi } from '../api/console'

interface Region {
  regionId: number
  regionName: string
  staffId: number
  regionDescribe: string
  storeId: number
}

interface Board {
  boardId: number
  boardName: string
  seat: number
  boardStatus: string  // 改为 string 类型，因为返回的是枚举字符串
  boardType: string
  regionId: number
}

interface Dish {
  dishId: number
  dishImage: string
  dishName: string
  price: number
  dishStatus: number
  dtId: number
  dishDescribe: string
}

interface OrderItem {
  orderItem: {
    itemId: number
    orderId: number
    dishId: number
    quantity: number
  }
  dish: Dish
}

interface Order {
  orderId: number
  boardId: number
  totalAmount: number
  discountAmount: number
  payableAmount: number
  orderType: number
  orderStatus: string
  placeOrderTime: number
  paymentTime: number
  remark: string
  shippingAddress: string
  uid: number
  items: OrderItem[]
}

// 数据状态
const regions = ref<Region[]>([])
const boards = ref<Board[]>([])
const activeRegion = ref('1')
const loading = ref(false)
const orderDialogVisible = ref(false)
const currentBoard = ref<Board | null>(null)
const currentOrder = ref<Order | null>(null)
const regionOrders = ref<Order[]>([]) // 添加区域订单数据存储

// 存储所有区域的餐桌数据
const allRegionsBoards = ref<Board[]>([])

// 根据区域筛选餐桌
const filteredBoards = computed(() => {
  if (activeRegion.value === 'all') {
    return boards.value
  }
  return boards.value.filter(board => board.regionId === Number(activeRegion.value))
})

// API接口
const fetchRegions = async () => {
  try {
    loading.value = true
    const params = new URLSearchParams()
    params.append('regionIds', '9')
    params.append('regionIds', '10')
    
    const response = await fetch(`http://localhost:8080/api/region?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'auth': '42'
      }
    })
    const result = await response.json()
    // 确保返回的数据结构正确
    if (result.code === 200 && result.data) {
      regions.value = result.data
    } else {
      throw new Error(result.message || '获取区域失败')
    }
  } catch (error) {
    console.error('获取区域失败:', error)
    ElMessage.error('获取区域失败')
  } finally {
    loading.value = false
  }
}

const fetchBoards = async (regionId: number) => {
  try {
    loading.value = true
    const params = new URLSearchParams()
    params.append('regionIds', regionId.toString())
    
    const response = await fetch(`http://localhost:8080/api/board?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'auth': '42'
      }
    })
    const result = await response.json()
    
    // 确保返回的数据结构正确
    if (result.code === 200 && result.data) {
      return result.data
    } else {
      throw new Error(result.message || '获取餐桌失败')
    }
  } catch (error) {
    console.error('获取餐桌失败:', error)
    ElMessage.error('获取餐桌失败')
    return []
  } finally {
    loading.value = false
  }
}

// 获取所有区域的餐桌数据
const fetchAllBoards = async () => {
  try {
    const allBoards: Board[] = []
    // 直接获取9和10区域的餐桌
    const regionBoards9 = await fetchBoards(9)
    const regionBoards10 = await fetchBoards(10)
    allBoards.push(...regionBoards9, ...regionBoards10)
    allRegionsBoards.value = allBoards
  } catch (error) {
    console.error('获取所有餐桌失败:', error)
    ElMessage.error('获取所有餐桌失败')
  }
}

// 处理区域切换
const handleRegionChange = (tab: string) => {
  activeRegion.value = tab
  if (tab === 'all') {
    boards.value = allRegionsBoards.value
  } else {
    boards.value = allRegionsBoards.value.filter(board => board.regionId === Number(tab))
  }
}

// 计算所有区域的可用餐桌总数
const getTotalAvailableTables = computed(() => {
  return allRegionsBoards.value.filter(board => board.boardStatus === 'UNINHABITED').length
})

// 计算当前区域的可用餐桌数量
const getCurrentRegionAvailableTables = computed(() => {
  if (activeRegion.value === 'all') {
    return getTotalAvailableTables.value
  }
  return boards.value.filter(board => 
    board.boardStatus === 'UNINHABITED' && 
    board.regionId === Number(activeRegion.value)
  ).length
})

// 计算当前区域的总餐桌数量
const getCurrentRegionTotalTables = computed(() => {
  if (activeRegion.value === 'all') {
    return allRegionsBoards.value.length
  }
  return boards.value.filter(board => 
    board.regionId === Number(activeRegion.value)
  ).length
})

// 获取餐桌状态样式
const getTableStatusClass = (status: string): string => {
  const statusMap: Record<string, string> = {
    'UNINHABITED': 'status-free',      // 无人
    'BOOKING': 'status-reserved',      // 预约
    'REPAST': 'status-occupied',       // 就餐
    'DISABLE': 'status-disabled'       // 禁用
  }
  return statusMap[status] || ''
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'UNINHABITED': '空闲',    // 无人
    'BOOKING': '已预订',      // 预约
    'REPAST': '就餐中',       // 就餐
    'DISABLE': '停用'         // 禁用
  }
  return statusMap[status] || '未知'
}

// 获取区域订单信息
const fetchRegionOrders = async (regionIds: number[]) => {
  try {
    const params = new URLSearchParams()
    regionIds.forEach(id => params.append('regionIds', id.toString()))
    
    const response = await fetch(`http://localhost:8080/api/orders/region?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'auth': '42'
      }
    })
    const result = await response.json()
    
    if (result.code === 200 && result.data) {
      console.log('获取到的订单数据:', result.data)
      return result.data
    } else {
      throw new Error(result.message || '获取区域订单失败')
    }
  } catch (error) {
    console.error('获取区域订单失败:', error)
    ElMessage.error('获取区域订单失败')
    return []
  }
}

// 计算就餐时长
const calculateDiningDuration = (boardId: number): string => {
  const board = allRegionsBoards.value.find(b => b.boardId === boardId)
  if (!board) return '0分钟'
  // 只有就餐中才显示用餐时长
  if (board.boardStatus !== 'REPAST') return '0分钟'
  const order = regionOrders.value.find(o => o.boardId === boardId)
  if (order && order.placeOrderTime && order.paymentTime) {
    const startTime = new Date(order.placeOrderTime)
    const endTime = new Date(order.paymentTime)
    const diffMinutes = Math.floor((endTime.getTime() - startTime.getTime()) / (1000 * 60))
    if (diffMinutes < 0) return '0分钟'
    if (diffMinutes < 60) {
      return `${diffMinutes}分钟`
    } else {
      const hours = Math.floor(diffMinutes / 60)
      const minutes = diffMinutes % 60
      return `${hours}小时${minutes}分钟`
    }
  }
  return '0分钟'
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  // 转换为分钟
  const minutes = Math.floor(diff / 1000 / 60)
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  }
  
  const hours = Math.floor(minutes / 60)
  if (hours < 24) {
    return `${hours}小时前`
  }
  
  const days = Math.floor(hours / 24)
  if (days < 30) {
    return `${days}天前`
  }
  
  // 如果超过30天，显示具体日期
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 获取订单状态文本
const getOrderStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    'PAID': '已支付',
    'TO_BE_PAID': '待支付',
    'CANCELED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

// 判断餐桌是否可点击
const isTableClickable = (board: Board): boolean => {
  return board.boardStatus !== 'DISABLE'
}

// 处理餐桌点击 - 优化订单详情获取
const handleTableClick = async (board: Board) => {
  if (!isTableClickable(board)) {
    return
  }
  currentBoard.value = board
  const order = regionOrders.value.find(o => o.boardId === board.boardId)
  
  if (order) {
    if (!order.items) { // 只在没有items数据时请求
      try {
        const result = await orderApi.getOrderItems(order.orderId)
        if (result.code === 200 && result.data) {
          order.items = result.data
        }
      } catch (error) {
        console.error('获取菜品失败:', error)
        ElMessage.error('获取菜品失败')
      }
    }
    currentOrder.value = order
  } else {
    currentOrder.value = null
  }
  
  orderDialogVisible.value = true
}

// 生命周期钩子
onMounted(async () => {
  try {
    loading.value = true
    // 1. 获取区域数据
    const regionsResult = await regionApi.getRegions([9, 10])
    if (regionsResult.code === 200 && regionsResult.data) {
      regions.value = regionsResult.data
      
      // 2. 并行获取所有餐桌数据
      const [boards9Result, boards10Result] = await Promise.all([
        boardApi.getBoards([9]),
        boardApi.getBoards([10])
      ])
      
      // 合并餐桌数据
      const allBoards = []
      if (boards9Result.code === 200 && boards9Result.data) {
        allBoards.push(...boards9Result.data)
      }
      if (boards10Result.code === 200 && boards10Result.data) {
        allBoards.push(...boards10Result.data)
      }
      allRegionsBoards.value = allBoards
      
      // 3. 获取所有订单数据
      const ordersResult = await orderApi.getRegionOrders([9, 10])
      if (ordersResult.code === 200 && ordersResult.data) {
        regionOrders.value = ordersResult.data
      }
      
      // 4. 设置初始显示
      activeRegion.value = 'all'
      boards.value = allRegionsBoards.value
    }
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.restaurant-layout {
  min-height: 100vh;
  background: #f8f9fa;
  position: absolute;
  top: 60px; /* header的高度 */
  left: 200px; /* sidebar的宽度 */
  right: 0;
  bottom: 0;
  overflow-y: auto;
}

.header {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
  padding: 16px 24px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.tab-group {
  display: flex;
  gap: 12px;
  max-width: 1200px;
  margin: 0 auto;
}

.tab-item {
  padding: 8px 24px;
  border-radius: 8px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s ease;
  user-select: none;
  position: relative;
  background: #fff;
  border: 1px solid transparent;
}

.tab-item:hover {
  background: #fff;
  border-color: #f5222d20;
  color: #f5222d;
}

.tab-item.active {
  background: #fff;
  color: #f5222d;
  border-color: #f5222d;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 3px;
  background: #f5222d;
  border-radius: 2px;
}

.tables-container {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.tables-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.table-card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
}

.table-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.card-header {
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.table-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
}

.card-body {
  padding: 16px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #666;
  font-size: 14px;
}

.info-item i {
  font-size: 16px;
  color: #8c8c8c;
}

.time-info {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #8c8c8c;
  font-size: 13px;
  padding-top: 12px;
  border-top: 1px dashed #f0f0f0;
}

/* 状态样式 */
.status-free .status-tag {
  background: #f6ffed;
  color: #52c41a;
}

.status-reserved .status-tag {
  background: #fff2e8;
  color: #fa541c;
}

.status-occupied .status-tag {
  background: #fff1f0;
  color: #f5222d;
}

.status-disabled .status-tag {
  background: #f5f5f5;
  color: #bfbfbf;
}

.status-disabled {
  opacity: 0.75;
  cursor: not-allowed;
}

.status-disabled:hover {
  transform: none;
  box-shadow: none;
}

@media screen and (max-width: 768px) {
  .header {
    padding: 12px 16px;
  }

  .tab-item {
    padding: 6px 16px;
    font-size: 13px;
  }

  .tables-container {
    padding: 16px;
  }

  .tables-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }

  .table-name {
    font-size: 16px;
  }
}

@media screen and (max-width: 480px) {
  .header {
    padding: 8px 12px;
  }

  .tab-group {
    gap: 8px;
  }

  .tab-item {
    padding: 6px 12px;
    font-size: 12px;
  }

  .tables-container {
    padding: 12px;
  }

  .tables-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .card-header {
    padding: 12px;
  }

  .card-body {
    padding: 12px;
  }

  .info-item {
    font-size: 13px;
  }
}

.order-dialog :deep(.el-dialog) {
  margin: 0 auto;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.order-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.order-details {
  padding: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.order-number {
  font-size: 16px;
  font-weight: 500;
  color: #2c3e50;
}

.order-status {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.status-paid {
  background: #f6ffed;
  color: #52c41a;
}

.status-unpaid {
  background: #fff2e8;
  color: #fa541c;
}

.status-canceled {
  background: #f5f5f5;
  color: #bfbfbf;
}

.order-info {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin: 20px 0;
}

.info-group {
  text-align: center;
}

.info-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}

.info-value {
  font-size: 15px;
  color: #2c3e50;
  font-weight: 500;
}

.info-value.price {
  color: #f5222d;
}

.dishes-list {
  margin-top: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  color: #606266;
  font-size: 14px;
}

.dish-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.dish-item:last-child {
  border-bottom: none;
}

.dish-info {
  flex: 1;
  margin-right: 16px;
}

.dish-main {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 4px;
}

.dish-name {
  font-size: 15px;
  color: #2c3e50;
  font-weight: 500;
}

.dish-quantity {
  font-size: 13px;
  color: #909399;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.dish-describe {
  font-size: 13px;
  color: #909399;
  line-height: 1.4;
  margin-top: 4px;
}

.dish-price-info {
  text-align: right;
  min-width: 100px;
}

.dish-price {
  display: block;
  font-size: 15px;
  color: #f5222d;
  font-weight: 500;
  margin-bottom: 4px;
}

.dish-unit-price {
  display: block;
  font-size: 12px;
  color: #909399;
}

.no-order {
  padding: 40px 20px;
}

.order-remark {
  margin-top: 20px;
}

.remark-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.remark-content {
  font-size: 14px;
  color: #2c3e50;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.info-value > div {
  margin-bottom: 4px;
}

.info-value > div:last-child {
  margin-bottom: 0;
}

.info-value .price {
  color: #f5222d;
  font-weight: 500;
}

.tables-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.stats-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stats-value {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

@media screen and (max-width: 768px) {
  .tables-stats {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
  }

  .stats-value {
    font-size: 20px;
  }
}

@media screen and (max-width: 480px) {
  .tables-stats {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .stats-card {
    padding: 12px;
  }

  .stats-value {
    font-size: 18px;
  }
}

.cursor-not-allowed {
  cursor: not-allowed !important;
}
</style>